<?php

namespace app\admin\model\shop;

use app\admin\model\goods\GoodsModel;
use think\Model;

class ShopGoodsModel extends Model
{
    protected $name = 'shop_goods';

    /**
     * Notes: 添加门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @param $goods_ids
     * @param $shop_id
     * @return true
     */
    public function add_shop_goods($goods_ids, $shop_id)
    {

        $old_goods_ids = $this->where('shop_id', $shop_id)->column('goods_id');

        $new_goods_ids = array_diff($goods_ids, $old_goods_ids);

        if (empty($new_goods_ids) || count($new_goods_ids) <= 0) {
            return true;
        }
        $data = [];
        foreach ($new_goods_ids as $v) {
            $data[] = [
                'shop_id' => $shop_id,
                'goods_id' => $v,
                'price' => GoodsModel::where('id',$v)->value('price') ?? 0,
            ];
        }
        $this->insertAll($data);

        return true;
    }


    /**
     * Notes: 删除门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @param $goods_ids
     * @param $shop_id
     * @return true
     */
    public function delete_shop_goods($goods_ids, $shop_id, $admin_id = 0)
    {

        foreach ($goods_ids as $v) {
            $shopGoodsModel = new ShopGoodsModel();
            $info = $shopGoodsModel->where('goods_id', $v)->where('shop_id', $shop_id)->find();
            if (!empty($info)) {
                if ($info['stock'] > 0) {
                    $log_data = [
                        'shop_id' => $shop_id,
                        'goods_id' => $v,
                        'number' => '-' . $info['stock'],
                        'before' => $info['stock'],
                        'after' => 0,
                        'type' => ShopGoodsStockLogModel::TYPE_DEL,
                        'op_admin_id' => $admin_id,
                        'createtime' => time(),
                    ];

                    ShopGoodsStockLogModel::add($log_data);
                }
            }
        }

        $this->whereIn('goods_id', $goods_ids)->where('shop_id', $shop_id)
            ->delete();
        return true;

    }


    public function shop()
    {
        return $this->belongsTo(Message::class, 'shop_id', 'id', [], 'LEFT')
            ->setEagerlyType(0);
    }


    public function goods()
    {
        return $this->belongsTo(GoodsModel::class, 'goods_id', 'id', [], 'LEFT')
            ->setEagerlyType(0);
    }
}